package com.yl.applicationsecurity.utils;

import com.alibaba.fastjson.*;
import javax.net.ssl.*;
import java.io.*;
import java.net.*;
import java.security.*;
import java.security.cert.*;
import java.util.*;

public class IASTClient {

    // 禁用 SSL 验证
    public static void disableSslVerification() {
        try {
            TrustManager[] trustAllCertificates = new TrustManager[]{
                    new X509TrustManager() {
                        public X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }

                        public void checkClientTrusted(X509Certificate[] certs, String authType) {
                        }

                        public void checkServerTrusted(X509Certificate[] certs, String authType) {
                        }
                    }
            };

            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCertificates, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

            HostnameVerifier allHostsValid = (hostname, session) -> true;
            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            e.printStackTrace();
        }
    }

    // 获取 IAST 应用程序 ID 列表
    public static List<String> getIastApp(String token) throws IOException {
        String url = "https://10.33.155.34:443/iast/api-v1/open-api/application/list?pageSize=100";
        HttpURLConnection connection = setupHttpConnection(url, token);
        String response = getResponse(connection);
        JSONObject jsonResponse = JSON.parseObject(response); // 使用 fastjson 解析
        JSONArray records = jsonResponse.getJSONObject("data").getJSONArray("records");

        List<String> appApplicationIdList = new ArrayList<>();
        for (int i = 0; i < records.size(); i++) {
            appApplicationIdList.add(records.getJSONObject(i).getString("applicationId"));
        }
        return appApplicationIdList;
    }

    // 获取 IAST 节点名称
    public static List<String> getIastNode(String token, List<String> appList) throws IOException {
        List<String> nodeList = new ArrayList<>();
        for (String appName : appList) {
            String url = "https://10.33.155.34:443/iast/api-v1/open-api/node/list?status=1&pageSize=1000&applicationId=" + appName;
            HttpURLConnection connection = setupHttpConnection(url, token);
            String response = getResponse(connection);
            JSONObject jsonResponse = JSON.parseObject(response); // 使用 fastjson 解析
            JSONArray records = jsonResponse.getJSONObject("data").getJSONArray("records");

            for (int i = 0; i < records.size(); i++) {
                nodeList.add(records.getJSONObject(i).getString("nodeName"));
            }
        }
        return clearNode(nodeList);
    }

    // 数据整理，类似于 Python 中的 clearNode 方法
    public static List<String> clearNode(List<String> nodeList) {
        List<String> result = new ArrayList<>();
        for (String item : nodeList) {
            String[] parts = item.split("-");
            if (parts.length > 2) {
                String trimmed = String.join("-", Arrays.copyOf(parts, parts.length - 2));
                result.add(trimmed);
            }
        }
        return result;
    }

    // 设置 HTTP 连接
    private static HttpURLConnection setupHttpConnection(String urlStr, String token) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:133.0) Gecko/20100101 Firefox/133.0");
        connection.setRequestProperty("Accept", "application/json, text/plain, */*");
        connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
        connection.setRequestProperty("XMAZE-OPENAPI-TOKEN", token);
        connection.setRequestProperty("Connection", "close");
        return connection;
    }

    // 获取 HTTP 响应
    private static String getResponse(HttpURLConnection connection) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        return response.toString();
    }

    // 获取 IAST Token
    public static String getIastToken() throws IOException {
        String url = "https://10.33.155.34:443/iast/api-v1/open-api/token/generate?appId=xmirror&key=Xmirror!%40%23123&expirationTimeMinutes=100";
        HttpURLConnection connection = setupHttpConnection(url);
        String response = getResponse(connection);
        JSONObject jsonResponse = JSONObject.parseObject(response); // 使用 fastjson 解析
        System.out.println(response);
        String str = jsonResponse.getString("data");
        System.out.println(str);
        return jsonResponse.getString("data");  // 获取 token
    }
    // 设置 HTTP 连接
    private static HttpURLConnection setupHttpConnection(String urlStr) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:133.0) Gecko/20100101 Firefox/133.0");
        connection.setRequestProperty("Accept", "application/json, text/plain, */*");
        connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
        connection.setRequestProperty("Connection", "close");
        return connection;
    }

    public static List<String>  getData() throws Exception {
        disableSslVerification();  // 禁用 SSL 验证
        String token = getIastToken();  // 替换为实际 token
        // 获取应用程序 ID 列表
        List<String> appList = getIastApp(token);
        // 获取 IAST 节点名称
        List<String> nodeList = getIastNode(token, appList);
        return nodeList;
    }


    // 主方法示例
    public static void main(String[] args) throws IOException {
        disableSslVerification();  // 禁用 SSL 验证
        String token = getIastToken();  // 替换为实际 token

        try {
            // 获取应用程序 ID 列表
            List<String> appList = getIastApp(token);
            // 获取 IAST 节点名称
            List<String> nodeList = getIastNode(token, appList);
            // 输出整理后的节点名称
            for (String node : nodeList) {
                System.out.println(node);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
